from datetime import datetime
from cache import cache
import re
import textwrap
from utils import fg, bg, fgbg
from xml.dom.minidom import parse, parseString

class mta:
	
	mta_status_url = 'http://www.mta.info/status/serviceStatus.txt'
	alternate_parking_url = "http://www.nyc.gov/html/dot/downloads/excel/altside2010.csv"
	fname = 'mtaalerts~.txt'
	
	def alerts(req):

		fullAlerts = req.startswith('/mta/full')
		cache.download(mta.mta_status_url, mta.fname)

		dom = parse(mta.fname)
		subway = dom.getElementsByTagName("subway")[0]
		lines = subway.getElementsByTagName("line")
		s = ''
		for line in lines:
			name = line.getElementsByTagName("name")[0].firstChild.nodeValue
			status = line.getElementsByTagName("status")[0].firstChild.nodeValue
			text = ''
			textNode = line.getElementsByTagName("text")[0]
			if textNode != None and textNode.firstChild != None:
				text = textNode.firstChild.nodeValue
			
			if fullAlerts == False:
				if status != 'GOOD SERVICE':
					status = fg(status, 'yellow')
				s += name.ljust(10) + ': ' + status + '\n'
				
			if status != 'GOOD SERVICE' and fullAlerts == True:
				s += name + '<br>' + text + '<br>================================<br>\n'
	
		if fullAlerts == False:
			s = '\033[2J' + s

		return s

	def parking(req):
		
		fullParking = req.startswith('/park/full')
		fname = 'altside~.txt'
		cache.download(mta.alternate_parking_url, fname, 720)
		s = cache.get(fname)

		today = datetime.today()
		lines = s.split('\n')
		lines.pop(0)
		p = 0
		s = ""
		for line in lines:
			cols = line.split(',')
			if len(cols) < 7:
				continue
			dd = datetime.strptime(cols[1], "%m/%d/%Y")
			d = dd - today
			if p == 0 and d.days >= 0:
				p = 1
			if p > 0:
				if dd.weekday() == 0 or dd.weekday() == 2 or dd.weekday() == 3 or dd.weekday() == 4:
					s += fg(datetime.strftime(dd, "%a %m/%d "), 'green')
					if fullParking == True:
						s += fg(cols[6], 'green') + "\n"
				else:
					s += datetime.strftime(dd, "%a %m/%d ")
					if fullParking == True:
						s += cols[6] + "\n"
				p += 1
			if p > 4:
				break
		
		h = ''
		if fullParking == True:
			h +=  '--- ' + fg('P', 'cyan') + 'arking ---\n'
		else:
			h += '+-- ' + fg('P', 'cyan') + 'arking: '

		s = h + s
		print('===='+s+'=======')
		return s
